
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import router from "@/router";
import store from "@/store";

router.beforeEach(async (to,form,next) => {
   let loginUser = store.state.user.loginUser;
   //如果之前没登录 自动登录
   if(!loginUser ||!loginUser.userRole) {
      await store.dispatch('user/getLoginUser');
      loginUser = store.state.user.loginUser;
   }
   //页面权限验证
  const needAccess = (to.meta.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
   //必须要登陆的才能访问的页面
   if(needAccess !== ACCESS_ENUM.NOT_LOGIN) {
     //没登陆跳转到登录页面
     if(!loginUser || !loginUser.userRole) {
       next(`user/login?redirect=${to.fullPath}`)
       return;

     }
     //如果登录但是没有权限 跳转到没有权限页面
     if(!checkAccess(loginUser,needAccess)){
       next("/noAuth")
     }
   }
 next();
});
